package com.test.study.ToolsUtils.java8;

import java.util.concurrent.RecursiveTask;

/**
 * RecursiveTask 这个表示有返回值 RecursiveAction表示没有返回值
 * fork JOIN 框架
 * 
 * @author huyong
 *
 */

public class ForkJoinCalculate extends RecursiveTask<Long> {

	private static final long serialVersionUID = 1L;
	private long start;
	private long end;
	public ForkJoinCalculate(long start,long end) {
		this.end=end;
		this.start=start;
	}
	/*
	 * 临界值
	 */
	private static final long THRESHOLD=10000;

	/**
	 * 这里实现累加
	 */
	@Override
	protected Long compute() {
		long length=end-start;
		if(length<=THRESHOLD) {
			//这里开始求和
			long sum=0;
			for(long i=start;i<=end;i++) {
				sum+=i;
			}
			return sum;
		}else {
			//这里开始拆分子任务
			long middle=(start+end)/2;
			ForkJoinCalculate left = new ForkJoinCalculate(start, middle);
			left.fork();//拆分子任务，同时压入线程队列
			ForkJoinCalculate right = new ForkJoinCalculate(middle+1, end);
			right.fork();//拆分子任务，同时压入线程队列
			return left.join()+right.join();
		}
	}

}
